package com.zretc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author: bLUeSuMMerDreamer
 * @createTime: 2020-08-25 16:57
 */
@CrossOrigin
@Controller
@RequestMapping("/fileDownload")
public class FileDownLoadController {
    /**
     * 下载头像
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/getSellerFace")
    public void getSellerFace(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String root = "D:/EDS/images/seller/";
        // 获取指定的文件名
        String faceName = request.getParameter("sellerLogo");
        // 关联文件
        writeFile(response, root, faceName);
    }
    /**
     * 下载商品图片
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/getProductFace")
    public void getProductFace(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String root = "D:/EDS/images/products/";
        // 获取指定的文件名
        String faceName = request.getParameter("productsLogo");
        // 关联文件
        writeFile(response, root, faceName);
    }

    private void writeFile(HttpServletResponse response, String root, String faceName) throws IOException {
        File file = new File(root + faceName);
        // 通过字节读取流 读文件
        // System.out.println(root + faceName);
        FileInputStream fis = new FileInputStream(file);
        // 字节数组输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        // 边读边写
        while ((n = fis.read(b)) != -1) { // 有数据可读
            // 写
            bos.write(b, 0, n);
        }
        fis.close();
        // 通过Servlet输出流将文件以字节数组的形式输出到网页上
        ServletOutputStream sos = response.getOutputStream();
        sos.write(bos.toByteArray());
        sos.flush();
        sos.close();
    }
}
